import { PageContainer } from '@ant-design/pro-components';
import { Button, message, Modal, Space, Table, Input, Switch,Divider  } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined ,EyeOutlined, SearchOutlined } from '@ant-design/icons';
import type { FC } from 'react';
import { useState, useEffect } from 'react';
import { useNavigate,useModel } from 'umi';

import {
  deptpage,
  deptDelete,
  deptUpdateStatus
} from '@/services/system/departmentmanage';
import { useOutletContext } from '@umijs/max';
import AuthorizedButton from '@/components/AuthorizedButton';
interface DepartmentType {
  id: string;
  departmentName: string;
  description: string;
  departmentType: number;
  sort: number;
  status: number;
  createTime: string;
  children?: DepartmentType[];
  fatherDepartmentId: string | null;
}
interface ButtonData {
  id: string;
  pageId: string;
  resourceName: string;
  icon?: string;
  action: string;
}
const DepartmentManage: FC = () => {
  const navigate = useNavigate();
  const [departments, setDepartments] = useState<DepartmentType[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const { buttonData } = useOutletContext<{ buttonData: ButtonData[] }>();
  const [searchText, setSearchText] = useState('');

  const { institutionId, institutionRoleId } = useModel('auth');
  useEffect(() => {

    fetchData();
  }, []);

  const handleSearch = (value: string) => {
    setSearchText(value);
    fetchData({ departmentName: value });
  };

  const fetchData = async (params: Record<string, any> = {}) => {
    try {
      const response = await deptpage({
        current: params?.current || 1,
        size: params?.pageSize || 10,
        institutionId: institutionId,
        institutionRoleId: institutionRoleId,
        ...params
      });

      if (response.code === 200) {
        console.log('response.data.records>',response);

        let filteredData = response.data;

        if (searchText && !params.departmentName) {
          filteredData = filteredData.filter((record: DepartmentType) =>
            record.departmentName.includes(searchText)
          );
        }

        setDepartments(filteredData);
      }
    } catch (error) {
      console.error(error);
    }
  };
  const columns = [
    {
      title: '部门名称',
      dataIndex: 'deptName',
      key: 'deptName',
      width: 180,
    },
    {
      title: '部门编号',
      dataIndex: 'id',

      width: 180,
    },
    {
      title: '上级部门',
      dataIndex: 'fatherDepartmentId',
      key: 'fatherDepartmentId',
      width: 150,
      render: (value: string | null) => value || '无（顶级部门）',
    },
    {
      title: '部门类型',
      dataIndex: 'departmentType',
      key: 'departmentType',
      width: 100,
      render: (value: number) => value === 0 ? '部门' : '其他',
    },
    {
      title: '部门排序',
      dataIndex: 'sort',
      key: 'sort',
      width: 100,
    },
    {
      title: '部门描述',
      dataIndex: 'fullName',
      key: 'fullName',
      ellipsis: true,
    },
    // {
    //   title: '状态',
    //   dataIndex: 'status',
    //   key: 'status',
    //   width: 100,
    //   render: (status: number, record: DepartmentType) => (
    //     <Switch
    //       checkedChildren="启用"
    //       unCheckedChildren="禁用"
    //       checked={status === 0}
    //       onChange={(checked) => handleStatusChange(record.id, checked)}
    //     />
    //   ),
    // },

    {
      title: '操作',
      key: 'action',
      width: 300,
      render: (_: any, record: DepartmentType) => (
        <span>
        <Space split={<Divider type="vertical" />}>
          <AuthorizedButton
            buttonData={buttonData}
            action="edit"
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            编辑
          </AuthorizedButton>
          <AuthorizedButton
            buttonData={buttonData}
            action="delete"
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            删除
          </AuthorizedButton>
          <AuthorizedButton
            buttonData={buttonData}
            action="view"
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
            style={{
              padding: 0,
              height: '22px',
              lineHeight: '22px',
            }}
          >
            详情
          </AuthorizedButton>
        </Space>
      </span>
      ),
    },
  ];

  const handleAdd = () => {
    navigate('/system/departmentmanage/add');
  };

  const handleEdit = (record: DepartmentType) => {
    navigate('/system/departmentmanage/edit', { state: { record } });
  };

  const handleView = (record: DepartmentType) => {
    navigate('/system/departmentmanage/view', { state: { record } });
  };

  const handleDelete = (record: DepartmentType) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除部门 "${record.deptName}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await deptDelete({
            departmentId: record.departmentId,
            institutionRoleId: institutionRoleId,
            institutionId: institutionId
          });

          if (response.code === 200) {
            message.success('删除成功');
            fetchData(); // 刷新列表
          } else {
            message.error(response.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除失败:', error);
          message.error('删除失败');
        }
      }
    });
  };

  const handleStatusChange = async (id: string, checked: boolean) => {
    try {
      const response = await deptUpdateStatus({
        id,
        status: checked ? 0 : 1  // 0 表示启用，1 表示禁用
      });

      if (response.code === 200) {
        message.success('状态修改成功');
        fetchData(); // 刷新列表数据
      } else {
        message.error(response.msg || '状态修改失败');
      }
    } catch (error) {
      console.error('状态修改失败:', error);
      message.error('状态修改失败');
    }
  };

  const rowSelection = {
    type: 'checkbox' as const,
    selectedRowKeys,
    onChange: (selected: React.Key[]) => {
      setSelectedRowKeys(selected);
    },
    checkStrictly: true,
    columnWidth: 60,
    columnTitle: '选择',
    getCheckboxProps: (record: DepartmentType) => ({
      name: record.id,
    }),
  };

  const convertToTableData = (data: DepartmentType[]): DepartmentType[] => {
    const map = new Map();
    const result: DepartmentType[] = [];

    // 第一步：将所有节点添加到 map 中
    data.forEach(item => {
      map.set(item.id, { ...item, children: [] });
    });

    // 第二步：建立父子关系
    data.forEach(item => {
      const node = map.get(item.id);
      if (!item.fatherDepartmentId) {
        result.push(node);
      } else {
        const parentNode = map.get(item.fatherDepartmentId);
        if (parentNode) {
          if (!parentNode.children) {
            parentNode.children = [];
          }
          parentNode.children.push(node);
        }
      }
    });

    // 第三步：移除空的 children 数组
    const removeEmptyChildren = (nodes: DepartmentType[]): DepartmentType[] => {
      return nodes.map((node: DepartmentType): DepartmentType => {
        if (node.children && node.children.length === 0) {
          const { children, ...rest } = node;
          return rest as DepartmentType;
        }
        if (node.children) {
          return {
            ...node,
            children: removeEmptyChildren(node.children)
          };
        }
        return node;
      });
    };

    return removeEmptyChildren(result);
  };

  const onExpand = (expanded: boolean, record: DepartmentType) => {
    if (expanded) {
      setExpandedKeys(prev => [...prev, record.id]);
    } else {
      setExpandedKeys(prev => prev.filter(key => key !== record.id));
    }
  };

  return (
    <div style={{ background: '#f0f2f5', minHeight: '100vh' }}>
      <PageContainer
        style={{
          background: '#fff',
          borderRadius: '8px',
          padding: '24px',
          margin: '24px'
        }}
      >
        <div style={{
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          marginBottom: 16
        }}>
          <AuthorizedButton
            buttonData={buttonData}
            action="add"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            新增
          </AuthorizedButton>

          <div style={{ width: '300px' }}>
            <Input
              placeholder="请输入部门名称进行搜索"
              value={searchText}
              onChange={e => handleSearch(e.target.value)}
              suffix={<SearchOutlined style={{ color: '#1890ff' }} />}
              style={{
                borderRadius: '20px',
                backgroundColor: '#f5f5f5',
                border: 'none',
                padding: '8px 16px'
              }}
            />
          </div>
        </div>

        <Table
          columns={columns}
          dataSource={departments}
          rowKey="id"
          rowSelection={rowSelection}
          expandable={{
            expandedRowKeys: expandedKeys,
            onExpand: onExpand,
            defaultExpandAllRows: false,
            expandRowByClick: true,
          }}
        />
      </PageContainer>
    </div>
  );
};

export default DepartmentManage;
